# -*- encoding: utf-8 -*-

# Filename:   apidemo.py
# Created on: 2018-07-28 20:34:51
# Author:     wuxc (https://github.com/wuxc)

import requests
import json

class ApiException(Exception):
    def __init__(self, code, msg):
        self.code = code
        self.msg = msg

    def __repr__(self):
        return "ApiException(%d, %s)" % (self.code, self.msg) 
    __str__ = __repr__

# 任务状态
STATE_PENDING = 0
STATE_RUNNING = 1
STATE_WAITING = 2
STATE_ERRWAITING = 3
STATE_CANCELING = 4
STATE_FINISHED = 5
STATE_CANCELED = 6
STATE_ABORTED = 7

# 任务指令
CMD_CANCEL = 2
CMD_VERIFY = 3


class JzAGVApi(object):
    def __init__(self, addr):
        self.addr = addr

    def get_one_robot(self, rid):
        r = requests.get(self.addr+"/api/v1/robots/%d" % rid)
        data = r.json()
        if r.status_code != 200:
            raise ApiException(int(data["code"]), data["msg"])
        return data

    def get_all_robots(self):
        r = requests.get(self.addr+"/api/v1/robots")
        data = r.json()
        if r.status_code != 200:
            raise ApiException(int(data["code"]), data["msg"])
        return data

    def create_mission(self, uuid, map_name, target=0, action=""):
        data = {"ref_uuid":uuid, "steps":[{"map_name":map_name, "target":target, "action":action}]}
        r = requests.post(self.addr+"/api/v1/missions", data=json.dumps(data))
        data = r.json()
        if r.status_code != 201:
            raise ApiException(int(data["code"]), data["msg"])
        return data

    def get_one_mission(self, mid):
        r = requests.get(self.addr+"/api/v1/missions/%d" % mid)
        data = r.json()
        if r.status_code != 200:
            raise ApiException(int(data["code"]), data["msg"])
        return data

    def get_one_mission_uuid(self, uuid):
        r = requests.get(self.addr+"/api/v1/uuid/missions/%s" % uuid)
        data = r.json()
        if r.status_code != 200:
            raise ApiException(int(data["code"]), data["msg"])
        return data

    ## Deprecated
    #def get_missions(self, offset=0, limit=100, sortby="", order=0):
    #    data = {}
    #    if offset > 0: data["offset"] = offset
    #    if limit > 0: data["limit"] = limit
    #    if sortby != "": data["sortby"] = sortby
    #    data["order"] = order
    #    r = requests.get(self.addr+"/api/v1/missions", data)
    #    data = r.json()
    #    if r.status_code != 200:
    #        raise ApiException(int(data["code"]), data["msg"])
    #    return data

    def create_mission_command(self, cmd, mid=None, uuid=None, sync=False):
        data = {"cmd":cmd, "sync":sync}
        if mid is not None:
            data["mission_id"] = int(mid)
        elif uuid is not None:
            data["mission_uuid"] = str(uuid)
        else:
            raise ValueError("mission id and uuid cannot be both None")
        r = requests.post(self.addr+"/api/v1/mscmds", data=json.dumps(data))
        data = r.json()
        if r.status_code != 200 and r.status_code != 201:
            raise ApiException(int(data["code"]), data["msg"])
        return data

    def check_mission_command(self, cid):
        r = requests.get(self.addr+"/api/v1/mscmds/%d" % cid)
        data = r.json()
        if r.status_code != 200:
            raise ApiException(int(data["code"]), data["msg"])
        return data

if __name__ == "__main__":
    api = JzAGVApi("http://192.168.1.100:8858")
    # 获取单个机器人信息
    try:
        print(api.get_one_robot(1))
    except Exception as e:
        print("get_one_robot", e)

    # ## 获取所有机器人信息
    # try:
    #     print(api.get_all_robots())
    # except Exception as e:
    #     print("get_robots", e)

    # ## 获取单个任务信息
    # try:
    #     print(api.get_one_mission(1))
    # except Exception as e:
    #     print("get_one_mission", e)
    #

    # uuid = "5.2.7"
    # map_name = "5y2r1"
    # ## 创建任务
    # try:
    #     print(api.create_mission(uuid, map_name,target=3))
    # except Exception as e:
    #     print("create_mission", e)
    #
    # ## 通过uuid获取单个任务信息
    # try:
    #     data = api.get_one_mission_uuid(uuid)
    #     print(data)
    # except Exception as e:
    #     print("get_one_mission_uuid", e)

    # ## 下发任务指令
    # try:
    #     data = api.create_mission_command(CMD_CANCEL, uuid=uuid, sync=True)
    #     print(data)
    #     ## 查询任务指令结果
    #     try:
    #         print(api.check_mission_command(data["id"]))
    #     except Exception as e:
    #         print("check_mission_command", e)
    # except Exception as e:
    #     print("create_mission_command", e)


